<?php
namespace app\common\model;
use think\Model;
abstract class Base extends Model{
    protected $primary_key;  //主键
    protected function initialize()
    {
        parent::initialize();
        $this->primary_key = $this->getPk();
    }

    /**
     * 保存/添加数据
     * @param  array $data
     * @param bool $allow
     * @return false|int|mixed
     */
    public function createData($data, $allow = true)
    {

        if (isset($data[$this->primary_key]))
        {
            if (is_numeric($data[$this->primary_key]) && $data[$this->primary_key] > 0)
            {
                $info = $this->find($data[$this->primary_key]);
                if(!$info){
                    $res = self::create($data, $allow);
                    $save = $res->getData();
                    return $save[$this->primary_key];
                }else{
                    $save = $this->allowField($allow)->save($data, [$this->primary_key => $data[$this->primary_key]]);
                    return $save;
                }
            } else{
                unset($data[$this->primary_key]);
                $res = self::create($data, $allow);
                $save = $res->getData();
                return $save[$this->primary_key];
            }
        } else
        {
            $res = self::create($data, $allow);
            $save = $res->getData();
            return $save[$this->primary_key];
        }
    }

    /**
     * 保存/编辑数据
     * @param array $data  数据
     * @param bool $allow 是否过滤字段
     * @return false|int
     */
    public function editData($data, $allow = true)
    {
        if (isset($data[$this->primary_key]))
        {
            if (is_numeric($data[$this->primary_key]) && $data[$this->primary_key] > 0)
            {
                $save = $this->allowField($allow)->save($data, [$this->primary_key => $data[$this->primary_key]]);
            } else{
                $save = $this->allowField($allow)->save($data);
            }
        } else{
            $save = $this->allowField($allow)->save($data);
        }
        return $save;
    }
}